package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no59;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] matrix = solution.generateMatrix(10);
        printArr(matrix);
    }

    public static void printArr(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }


    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        writeMatrix(matrix, n, 0, 1);
        return matrix;
    }


    public void writeMatrix(int[][] matrix, int n, int cur, int number) {
        if (cur <= n / 2) {
            for (int i = cur; i < n - cur; i++) {
                matrix[cur][i] = (number++);
            }
            int y = n - cur - 1;
            for (int i = cur + 1; i < n - cur; i++) {
                matrix[i][y] = (number++);
            }
            int x = n - cur - 1;
            if (x > cur) {
                for (int i = n - cur - 2; i >= cur; i--) {
                    matrix[x][i] = (number++);
                }
            }
            if (y > cur) {
                for (int i = n - cur - 2; i > cur; i--) {
                    matrix[i][cur] = (number++);
                }
            }
            writeMatrix(matrix, n, cur + 1, number);
        }
    }

}
